﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

using Tszy.Unlimited.Base.Infrastructure.SlideCaptcha.Generator;
using Tszy.Unlimited.Base.Infrastructure.SlideCaptcha.Resources;
using Tszy.Unlimited.Base.Infrastructure.SlideCaptcha.Resources.Handler;
using Tszy.Unlimited.Base.Infrastructure.SlideCaptcha.Resources.Provider;
using Tszy.Unlimited.Base.Infrastructure.SlideCaptcha.Storage;
using Tszy.Unlimited.Base.Infrastructure.SlideCaptcha.Validator;

namespace Tszy.Unlimited.Base.Infrastructure.SlideCaptcha;

public static class CaptchaServiceCollectionExtensions
{
    public static CaptchaBuilder AddSlideCaptcha(this IServiceCollection services, IConfiguration configuration, Action<CaptchaOptions>? optionsAction = default)
    {
        services.Configure<CaptchaOptions>(configuration?.GetSection("SlideCaptcha"));
        if (optionsAction != null) services.PostConfigure(optionsAction);

        var builder = new CaptchaBuilder(services);
        services.AddSingleton<IResourceProvider, OptionsResourceProvider>();
        services.AddSingleton<IResourceProvider, EmbeddedResourceProvider>();
        services.AddSingleton<IResourceHandlerManager, CachedResourceHandlerManager>();
        services.AddSingleton<ICaptchaImageResourceManager, DefaultCaptchaImageResourceManager>();
        services.AddSingleton<ICaptchaImageGenerator, DefaultCaptchaImageGenerator>();
        services.AddSingleton<IResourceHandler, FileResourceHandler>();
        services.AddSingleton<IResourceHandler, EmbeddedResourceHandler>();
        services.AddScoped<ICaptcha, DefaultCaptcha>();
        services.AddScoped<IStorage, DefaultStorage>();
        services.AddScoped<IValidator, SimpleValidator>();
        return builder;
    }
}